package com.docMan.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import com.docMan.dao.DangAnFromOaDao;
import com.docMan.dao.pojo.Dangan;
import com.docMan.dao.pojo.DocFile;
import com.docMan.dao.pojo.DocFtp;
import com.docMan.service.DocFileService;
import com.docMan.service.DocRecordService;
import com.docMan.utils.CastUtil;
import com.docMan.utils.FinalConfig;
import com.docMan.utils.FtpUtils;
import com.docMan.utils.GetRealPath;
import com.docMan.utils.PropsUtil;
import com.docMan.utils.Tif2Pdf;
import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport {
	private InputStream attachstream;
	private String fileName;
	private int id=0;
	private DocFileService docFileService;
	private DocRecordService docRecordService;
	private String indexFrom="0";
	private DangAnFromOaDao danganDao;
	private HttpSession session;
//	@Action(value = "dowloadFile", results = { @Result(name = "download", type = "stream", params = {
//			"contentType", "text/plain", "inputName", "attachstream",
//			"contentDisposition", "attachment;filename=\"${fileName}\"", 
//			"bufferSize","8192" }) })
	
	public String downloadFile() {
		try {
			if(indexFrom.equals(FinalConfig.INDEX_FORM_UPLOAD)){
				return	getFileFromUpload();
			}else  {
				return getFileFromOa();
			}
//			indexFrom.equals(FinalConfig.INDEX_FORM_OA)
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.setAttribute("message", "您所查看的文件不存在");
			return "error";
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
	}
	
	/**
	 * 文件来源自上传的fpt文件
	 * @return
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	private String getFileFromUpload() throws FileNotFoundException, UnsupportedEncodingException{
		DocFile docFile=docFileService.getById(id);
		String realPath=GetRealPath.getPath(docFile.getPath());
		if(!docFileService.canDownload(id)){
//			Map<String, Object> session=ActionContext.getContext().getSession();
			session.setAttribute("message", "你没有权限下载该文件");
			return "error";
		}
		Random random1=new Random(10000);
		Random random2=new Random(10000);
		String localPath = FinalConfig
				.getFtpDownloadLocalPath(random1.nextInt(10000)+random2.nextInt(10000));// 这里应该是session中的humanid
		FtpUtils.downloadFile(FinalConfig.getDocFtp(), docFile.getFileName(), realPath,localPath );
		attachstream=new FileInputStream(localPath+docFile.getFileName());
		fileName=URLEncoder.encode(docFile.getFileName(), "UTF-8");
		docRecordService.record(id, FinalConfig.FILE_DOWNLOAD);
		return "download";
	}
	
	
	private String getFileFromOa() throws IOException{
		
		DocFtp docFtp=getOaFtp();
		List<Dangan> dangans=danganDao.findNoCache("select da from Dangan da where da.vrecid=?", new BigDecimal(id));
		if(dangans.size()>0){
			Random random1=new Random(10000);
			Random random2=new Random(10000);
			String localPath = FinalConfig
					.getFtpDownloadLocalPath(random1.nextInt(10000)+random2.nextInt(10000));// 这里应该是session中的humanid
			String fullPath=dangans.get(0).getLj();
			String realPath=fullPath.substring(0, fullPath.lastIndexOf("/")+1);
			String oaFileName=fullPath.substring(fullPath.lastIndexOf("/")+1,fullPath.length());
//			String oaFileName="5.tif";
			String pdfName="";
			FtpUtils.downloadFile(docFtp, oaFileName, realPath,localPath );
//			FtpUtils.downloadFile(docFtp, oaFileName, "/doc1",localPath );
			if(oaFileName.endsWith("tif")||oaFileName.endsWith("tiff")){
				pdfName=oaFileName.replace("tiff", "pdf").replace("tif", "pdf");
				Tif2Pdf.convert(localPath+oaFileName, localPath+pdfName);
			}else{
				pdfName=oaFileName;
			}
			attachstream=new FileInputStream(localPath+pdfName);
			fileName=URLEncoder.encode(oaFileName, "UTF-8");
			docRecordService.record(id, FinalConfig.FILE_DOWNLOAD);
		}
		return "oa";
	}
	
	
	private DocFtp getOaFtp() throws FileNotFoundException, UnsupportedEncodingException{
		String filePath="config.properties";
		Map<String, String> props=PropsUtil.loadPropsToMap(filePath);
		DocFtp docFtp=new DocFtp();
		docFtp.setIp(props.get("oa.ftp.url"));
		docFtp.setServerName(props.get("oa.ftp.url"));
		docFtp.setUsername(props.get("oa.ftp.username"));
		docFtp.setPassword(props.get("oa.ftp.password"));
		docFtp.setDiskName(props.get("oa.ftp.diskname"));
		docFtp.setPort(CastUtil.castInt(props.get("oa.ftp.port")));
		return docFtp;
	}
	
	@Resource
	public void setDocRecordService(DocRecordService docRecordService) {
		this.docRecordService = docRecordService;
	}
	@Resource
	public void setDocFileService(DocFileService docFileService) {
		this.docFileService = docFileService;
	}
	@Resource(name="danganDao")
	public void setDanganDao(DangAnFromOaDao danganDao) {
		this.danganDao = danganDao;
	}
	@Autowired
	public void setSession(HttpSession session) {
		this.session = session;
	}
	public String getIndexFrom() {
		return indexFrom;
	}




	public void setIndexFrom(String indexFrom) {
		this.indexFrom = indexFrom;
	}




	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}


	public String getFileName() {
		return fileName;
	}


	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getAttachstream() {
		return attachstream;
	}

	public void setAttachstream(InputStream attachstream) {
		this.attachstream = attachstream;
	}
}
